// pages/datail/datail.js
//var dateTimePicker = require('../../utils/dateTimer.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productid : '',
    token : '',

    tabNow:0,
    tabList:['设备详情','报警记录','历史数据'],
    currentdevice:[],
    locationList:[],
    locationData:[],

    recordData:[],

    startdate: '开始日期',//默认起始时间  
    enddate: '结束日期',//默认结束时间 
    selectTime:false,

    shows: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectDatas: ['30条', '50条', '100条','all'], //下拉列表的数据
    indexs: 0, //选择的下拉列 表下标,

    chartData: {},//数据里包含了 categories x轴数组，series 需要绘制的曲线数组
    opts: {//配置项，这里只展示了部分，关于配置项的详细解释可以到官网文档查看
      color: ["#1890FF", "#91CB74"],
      enableScroll: true,//是否开启滚动
      dataLabel: false,
      xAxis: {
        disableGrid: true,//是否 不纵向绘制网格
        type: 'grid',
        gridType: 'dash',

        itemCount: 30,//x轴单屏显示数据的数量，默认为5个 ————滚动需要的配置
        labelCount: '3',//x轴单屏显示标签的数量，默认为5个
        scrollBackgroundColor: '#00000000',//默认为 #EFEBEF
        scrollColor: '#DEE7F7',//默认为 #A6A6A6
        rotateLabel: false,//开启文字旋转功能

        
      },
      yAxis: {
        gridType: "dash",
        dashLength: 2,
        title:'dasdas',
      },
      extra: {
        line: {
         type: "curve",
         width: 2,
         activeType: "hollow"
        }
      }
    
    },

    timer:null,

  },

  //切换不同的tab 
  selectTab (e) { 
    this.setData({
        tabNow: e.currentTarget.dataset.id
    })
    //console.log('tabNow=',e.currentTarget.dataset.id)
  },

  //获取当前设备数据
  getData() { 
    //获取页面栈  
    var pages = getCurrentPages(); 
    //console.log(pages)
    if(pages.length > 1){ 
      //上一个页面实例对象 
      var prePage = pages[pages.length - 2]; 
      //console.log(prePage)
      // 调用上个页面的数据
      var onlineindex = prePage.data.onlineindex
      var offlineindex = prePage.data.offlineindex
      if(offlineindex.length == 0){
        this.setData({
          currentdevice:prePage.data.onlineList[onlineindex],
          productid:prePage.data.productid,
          token  : prePage.data.token
        })
        //console.log('在线',this.data.currentdevice)
      }else{
        this.setData({
          currentdevice:prePage.data.offlineList[offlineindex]
        })
        //console.log('离线',this.data.currentdevice)
      }
      
    }   
  },

  //获取地址
  getLocation(){
    var that = this
    var title = that.data.currentdevice.title
    let locationList = wx.getStorageSync('locationList')
    //console.log(locationList.length)
    if(locationList.length > 0){
      let locationData = locationList.find(function(locationList,index,arrs){return locationList.title === title })
      //console.log(locationData)
      if(locationData == undefined){
        that.setData({
          locationData:[{
            title:title,
            location:''
          }]
        })
      }else{
        that.setData({
          locationData:locationData
        })
      }
      //console.log("locationList", that.data.locationList)
      //console.log("locationData", that.data.locationData.location)
    }
    
  },

  //保存地址信息
  locationInput(options){
    var that = this
    //点击了键盘上的完成按钮
    var title = that.data.currentdevice.title
    let locationList = wx.getStorageSync('locationList')
    let locationData = [{
      title:title,
      location:options.detail.value
    }]
    //console.log("location", options.detail.value)
    if(options.detail.value == '') {
      wx.showToast({
        title: '内容为空',
        icon: 'error',
      });
    }else{
      if(locationList.length == 0){
        wx.setStorageSync('locationList',[])
        wx.setStorageSync('locationList',locationData)
        //console.log("添加" , wx.getStorageSync('locationList')) 
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        });
      }else{
        var filterNum = locationList.find(function(locationList,index,arrs){return locationList.title === title });
        if(filterNum == undefined){
          locationList = locationList.concat(locationData)
          wx.setStorageSync('locationList',locationList)
          //console.log("增加" , wx.getStorageSync('locationList')) 
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
        }else{
          for(var index in locationList){
            if(locationList[index].title == title){
              locationList[index].location = options.detail.value
              wx.setStorageSync('locationList',locationList)
              //console.log("修改" , wx.getStorageSync('locationList')) 
              wx.showToast({
                title: '修改成功',
                icon: 'success'
              });
            }
          }
        }
      }
    }
  },

  //获取历史数据
  getHistoryDatapoints(){
    var that = this
    var productid = that.data.productid
    var token = that.data.token
    var title = that.data.currentdevice.title
    var startdate = that.data.startdate + 'T'+ '00:00:00'
    var enddate = that.data.enddate + 'T'+ '23:29:59'
    var selectTime = that.data.selectTime
    
    //console.log(url)
    if(selectTime == true){
      wx.request({
        url: 'https://iot-api.heclouds.com/datapoint/history-datapoints?product_id=' + productid + '&device_name=' + title + '&start=' + startdate + '&end=' + enddate + '&limit=6000&sort=ASC',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': token
        },
        //query:{},
        data: {
        
        },
        method: 'GET',
        success:(res)=>{
          //console.log(res.data.data)
          if(res.data.data== null){
            wx.showToast({
              title: '数据无',
              icon: 'error',
            });
          }else{
            
            // 进行数据处理
            var categories = []
            var value = []
            var state = []
            let data = res.data.data.datastreams
            console.log(data)
            if(res.data.data.count == 0){
              wx.showToast({
                title: '数据无',
                icon: 'error',
              });
            }else{
              for(var index in data[0].datapoints){
                categories[index] = data[0].datapoints[index].at.substring(6,16)
                //console.log(data[1].datapoints[index].value)
                if(data[1].datapoints[index].value == undefined){
                  wx.showToast({
                    title: '数据解析错误',
                    icon: 'error',
                  });
                }else{
                  if(data[0].id == 'gas_value'){
                    value[index] = data[0].datapoints[index].value
                    state[index] = data[1].datapoints[index].value
                  }else{
                    value[index] = data[1].datapoints[index].value
                    state[index] = data[0].datapoints[index].value
                    //console.log(index)
                  }
                }
              }
              let datas = { // 数据里包含了 categories x轴数组，series 需要绘制的曲线数组
                categories: categories,
                series: [
                  {
                    name: "浓度值",
                    data: value
                  },
                  {
                    name: "状态值",
                    data: state
                  }
                ]
              };
              //console.log(datas)
              this.setData({
                chartData : datas
              })
            } 
          }
        }
      })  
    }
  },

  //转到日期选择
  godatasel(){
    wx.navigateTo({
      url: '/pages/datasel/datasel'
    })
  },
  
  // 点击下拉显示框
  selectTaps() {
    this.setData({
      shows: !this.data.shows,
    });
  },

  // 点击下拉列表
  optionTaps(e) {
    var opts = this.data.opts
    let Indexs = e.currentTarget.dataset.index; //获取点击的下拉列表的下标
    console.log(Indexs)
    this.setData({
      indexs: Indexs,
      shows: !this.data.shows
    });
    if(Indexs == 0){
      opts.enableScroll = true
      opts.xAxis.itemCount = 30
      this.setData({
        opts:opts
      });
    }
    if(Indexs == 1){
      opts.enableScroll = true
      opts.xAxis.itemCount = 60
      this.setData({
        opts:opts
      });
    }
    if(Indexs == 2){
      opts.enableScroll = true
      opts.xAxis.itemCount = 100
      this.setData({
        opts:opts
      });
    }
    if(Indexs == 3){
      opts.enableScroll = false
      opts.xAxis.itemCount = ''
      this.setData({
        opts:opts
      });
    }
    console.log(this.data.opts)

  },


  //报警记录
  getRecord(){
    var that = this
    var title = that.data.currentdevice.title
    let alarmRecord = wx.getStorageSync('alarmRecord')
    var recordData = alarmRecord.filter(function(alarmRecord,index,arrs){return alarmRecord.title == title})
    that.setData({
      recordData:recordData
    })
  },

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var that = this  
    that.getData()
    //wx.clearStorageSync('locationList') //清除
    that.getLocation()
    that.getRecord()
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this
    //在这里写需要定时刷新的代码
    that.setData({
      timer:setInterval(function(){
        if(that.data.currentdevice.online == true){
          that.getData()
          //console.log('浓度值刷新了')
        }
      },1000)
    })
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.timer);  //清除定时器
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer);   //清除定时器
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
